import os
import requests
from alibabacloud_imageenhan20190930.client import Client
from alibabacloud_imageenhan20190930.models import MakeSuperResolutionImageAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
from config import Config   as myConfig


def super_resolution(image_path):
    """
    图像超分辨率增强函数
    """
    SAVE_PATH = myConfig.PATH_IMAGE_SUPER_RESOLUTION
    
    config = Config(
    # 创建AccessKey ID和AccessKey Secret，请参考https://help.aliyun.com/document_detail/175144.html。
    # 如果您用的是RAM用户的AccessKey，还需要为RAM用户授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html
    # 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
    access_key_id="LTAI5tEjriqJU1PhpsG31VDA",
    access_key_secret="jYr2LWv3ohluUvbSvnSlMkVAtcHYu4",
    # 访问的域名
    endpoint='imageenhan.cn-shanghai.aliyuncs.com',
    # 访问的域名对应的region
    region_id='cn-shanghai'
    )
    
    # 打开图像文件
    img = open(image_path, 'rb')
    make_super_resolution_image_request = MakeSuperResolutionImageAdvanceRequest(
        url_object=img,
        mode='base',    upscale_factor=2
    )
    
    runtime = RuntimeOptions()
    
    try:
        # 初始化Client
        client = Client(config)
        response = client.make_super_resolution_image_advance(make_super_resolution_image_request, runtime)
        
        # 获取结果URL
        if hasattr(response.body, 'data') and response.body.data:
            result_url = response.body.data.url
            
            # 下载图像到pic文件夹
        
            # 下载文件
            response_download = requests.get(result_url)
            if response_download.status_code == 200:
                with open(SAVE_PATH, 'wb') as f:
                    f.write(response_download.content)
                print(f"图像已保存到: {SAVE_PATH}")
                return SAVE_PATH
            else:
                print(f"下载失败，状态码: {response_download.status_code}")
                return None
        else:
            print("API返回结果为空")
            return None
            
    except Exception as e:
        print(f"处理失败: {str(e)}")
        return None
    finally:
        img.close()

